package Services

import(
	"github.com/gin-gonic/gin"
	"fmt"
	"net/http"
	"gin/Databases"
	"gin/Common"
	"encoding/json"
	"time"
)

/*
type TaskDetailData struct {
	Fid string `db:"Fid" json:"task_id"`
    TaskDate string `db:"Ftask_date" json:"task_date"`
    EntityName string `db:"Fentity_name" json:"entity_name"`
    StartDate string `db:"Fstart_date" json:"start_date"`
    CustomWord string `db:"Fcustom_word" json:"custom_word"`
    Url string `db:"Furl" json:"url"`
}
*/
type DisplayTaskByUserCgi struct {
	Common.CgiBase
	TaskClassId []int
	TaskList []TaskDetailData
}


func (cgi *DisplayTaskByUserCgi)quertTaskDetail() {
	sql := "select Fid,Ftask_date,Fentity_name,Fstart_date,Fcustom_word,Furl from db_custom_task where Femail=? order by Fentity_name desc;"
	err := Databases.Db.Select(&cgi.TaskList, sql, cgi.Input["user"])
	if err != nil {
		fmt.Println("exec failed, ", err)
		panic("query data fail")
	}
}

func (cgi *DisplayTaskByUserCgi)transformTask() (string){
    str, _ := json.Marshal(cgi.TaskList)
    str_res := string(str)
    return str_res
}

func (cgi *DisplayTaskByUserCgi)processParam(c *gin.Context) {
	time_now := time.Now()
	cgi.Input["limit_date"] = time_now.AddDate(0, 0, -1 * 30).Format("2006-01-02")
	cgi.Input["user"] = c.Query("user")
}

func DisplayTaskByUser(c *gin.Context) {
	defer func(){
		fmt.Println("开始处理异常")
		if err:=recover();err!=nil{
			fmt.Println("error:",err)
			c.JSON(http.StatusOK, gin.H{
		        "result": -1,
		        "msg":    err,
		        "data": "{}",
		    })
		}
	}()


	var cgi DisplayTaskByUserCgi
	cgi.Init(c)
	cgi.processParam(c)
	cgi.quertTaskDetail()

	json_res := cgi.transformTask()

    c.JSON(http.StatusOK, gin.H{
        "result": 0,
        "msg":    "success",
        "data": json_res,
    })

}

